<template>
  <div >
    <div class="content">
      <el-table
        ref="multipleTable"
        :data="evaluateData"
        height="450"
        highlight-current-row
        border
        style="width: 90%;margin-left: 5%"
        @current-change="handleSelectionChange"
      >

        <el-table-column prop="casNo" width="110" label="Cas号"/>
        <el-table-column prop="baseinfoYwmc" width="320" label="英文名称"/>
        <el-table-column prop="baseinfoZwmc" label="中文名称"/>
        <el-table-column prop="wzlb" label="物质类别"/>
        <el-table-column prop="process" label="工艺"/>
        <el-table-column prop="prove" width="80px" label="证明">
          <template slot-scope="scope">
            <el-button type="view" size="small" @click="getProveFiles(scope.row.casNo)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="handle" width="80px" label="操作">
          <template slot-scope="scope">
            <el-button  type="danger" size="small" @click="delEvaluateData(scope.row.casNo)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="bottom">
      <el-button type="primary" @click="exportWord()">生成报表</el-button>
    </div>
    <el-dialog title="证明文件" :visible.sync="proveVisible">
      <el-row v-for="proveFile in proveFiles" :key="proveFile.fileName">
        <el-button
          type="primary"
          @click="downloadFile(proveFile)"
        ><i class="el-icon-download el-icon--left"/>npu
          {{ proveFile.fileName }}
        </el-button>
      </el-row>
    </el-dialog>
  </div>
  <!--  <script src="js/plugins/docxtemplater/imagemodule.js"></script>-->

</template>
<script>
import docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import JSZipUtils from 'jszip-utils'
import {saveAs} from 'file-saver'
import ImageModule from "docxtemplater-image-module-free";

export default {
  data() {
    return {
      currentRow: null,
      multipleSelection: '',
      evaluateData: [],
      proveVisible: false,
      proveFiles: []
    }
  },
  mounted() {
    this.loadData()
    console.log("ssssssssssssssssssssss",this.multipleSelection)
  },
  methods: {

    loadData() {
      this.$api.data.getEvaluateData().then((res) => {
        this.evaluateData = res.data
        console.log('datavue', this.evaluateData)
      })
    },
    getProveFiles(val) {
      this.$api.data.findProveByCas({casNo: val}).then((res) => {
        console.log(res.data)
        this.proveFiles = res.data

        this.proveVisible = true
      })
    },
    delEvaluateData(val) {
      //弹框询问
      this.$confirm('此操作将删除选中元素，是否继续？','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.data.deleteEvaluateData(val).then((res) => {
          this.loadData()
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      // console.log(id)
    },
    downloadFile(file) {
      console.log(file.fileName)
      const params = {cas: file.casNo, filename: file.fileName}
      this.$api.data.downloadProve(params).then((res) => {
        console.log(res)
      })
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log("val;;;;;;",val)
    },
    // 点击导出成word文档
    base64DataURLToArrayBuffer(dataURL) {
      const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
      if (!base64Regex.test(dataURL)) {
        return false;
      }
      const stringBase64 = dataURL.replace(base64Regex, "");
      let binaryString;
      if (typeof window !== "undefined") {
        binaryString = window.atob(stringBase64);
      } else {
        //新版本nodejs已经不支持使用new Buffer了，这里只需要把new Buffer换成Buffer.from
        // binaryString = new Buffer(stringBase64, "base64").toString("binary");
        binaryString = Buffer.from(stringBase64, "base64").toString("binary");
      }
      const len = binaryString.length;
      const bytes = new Uint8Array(len);
      for (let i = 0; i < len; i++) {
        const ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
      }
      return bytes.buffer;
    },
    // 点击导出word
    exportWord: function () {
      const that = this
      if (this.multipleSelection.casNo == null) {
        this.$message({
          message: '请选择一个要生成报表的元素',
          type: 'error'
        })
      } else {
        // 读取并获得模板文件的二进制内容
        JSZipUtils.getBinaryContent('../../../static/template.docx', function (error, content) {
          // 抛出异常
          if (error) {
            throw error
          }

          // 图片处理
          const opts = {}
          opts.centered = true   // 图片居中，在word模板中定义方式为{%%image}
          opts.fileType = 'docx'
          opts.getImage = function (url) {
            console.log("图片的base64流", url)
            return that.base64DataURLToArrayBuffer(url)
          }
          opts.getSize = function () {
            return [350, 240]
          }
          const imageModule = new ImageModule(opts)
          // 创建一个PizZip实例，内容为模板的内容
          const zip = new PizZip(content)
          // 创建并加载docxtemplater实例对象
          const doc = new docxtemplater().loadZip(zip)

          doc.attachModule(imageModule)
          doc.loadZip(zip)

          // 设置模板变量的值
          doc.setData({
            baseinfozwmc: that.multipleSelection.baseinfoZwmc,
            baseinfocasNo: that.multipleSelection.casNo,
            baseinfoYwmc: that.multipleSelection.baseinfoYwmc,
            baseinfoFzs: that.multipleSelection.baseinfoFzs,
            baseinfo_xdfzzl: that.multipleSelection.baseinfo_xdfzzl,
            picBase64: that.multipleSelection.picBase64,
            lhsxbSrjd: that.multipleSelection.lhsxbSrjd,
            lhsxbBhzqy: that.multipleSelection.lhsxbBhzqy,
            waterPfl: that.multipleSelection.waterPfl,
            airPfl: that.multipleSelection.airPfl,
            soilPfl: that.multipleSelection.soilPfl,
            soilPfxs: that.multipleSelection.soilPfxs,
            fixation: that.multipleSelection.fixation,
            airPfxs: that.multipleSelection.airPfxs,
            residualLiquor: that.multipleSelection.residualLiquor,
            process: that.multipleSelection.process,
            fiber: that.multipleSelection.fiber,
            zjWzyl: that.multipleSelection.zjWzyl,
            zjDjl: that.multipleSelection.zjDjl,
            zjPfyzb: that.multipleSelection.zjPfyzb,
            zjJobtime: that.multipleSelection.zjJobtime,
            jjFzpl: that.multipleSelection.jjFzpl,
            jjYjl: that.multipleSelection.jjYjl,
            jjFzpbl: that.multipleSelection.jjFzpbl,
            jjYxcfhl: that.multipleSelection.jjYxcfhl,
            wzlb: that.multipleSelection.wzlb,
            yjbz: that.multipleSelection.yjbz,
            airFwcs: that.multipleSelection.airFwcs,
            waterFwcs: that.multipleSelection.waterFwcs,
            yzbz: that.multipleSelection.yzbz,

            'table1': [
              {name: '1', price: '2'},
              {name: '2', price: '5'}
            ]
          })
          console.log('this.evaluateData==')
          try {
            // 用模板变量的值替换所有模板变量
            doc.render()
          } catch (error) {
            // 抛出异常
            const e = {
              casNo: error.casNo
            }
            console.log(JSON.stringify({error: e}))
            throw error
          }
          // 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
          const out = doc.getZip().generate({
            type: 'blob',
            mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
          })
          // 将目标文件对象保存为目标类型的文件，并命名
          const date = new Date()
          saveAs(out, '环境评估报告' + date.toLocaleDateString() + '.docx')
        })
      }

    }
  }
}
</script>

<style scoped lang="scss">
.el-row {
  margin-bottom: 10px;

  &:last-child {
    margin-bottom: 0;
  }
}

h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}

;
.content {
  position: absolute;
  float: left;
  top: 10%;
  left: 10%;
  right: 10%;
}

.bottom {
  position: absolute;
  float: left;
  bottom: 10%;
  left: 10%;
  right: 10%;
}
</style>
